package com.yfp.client.util;

import com.yfp.client.generator.TokenGenerator;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Description: 获取当前用户信息
 *
 * @CreateDate: 2024/5/16 10:51
 * @UpdateUser:
 * @UpdateDate: 2024/5/16 10:51
 * @UpdateRemark: 暂无修改
 * @Version: 1.0
 */
@Slf4j
public class SecurityUtils {

    /**
     * 获取当前登录用户对象
     * @return
     */
    public static Claims getClient() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 从 http 请求头中取出 token
        String token = request.getHeader("Authorization");
        Claims claims = TokenGenerator.parseJWT(token);
        return claims;
    }

    /**
     * 获取当前登录用户ID
     * @return
     */
    public static String getClientId() {
        // return "547";
       return getClient().get("clientId").toString();
        // return "3737";
    }

    /**
     * 获取当前登录用户手机号码
     * @return
     */
    public static String getClientMobile() {
        return getClient().get("mobile").toString();
    }

    /**
     * 获取当前登录用户城市
     * @return
     */
    public static String getCityName() {
        try {
           return getClient().get("cityName").toString();
            // return "慕容梓晨";
        } catch (Exception e) {
            log.error("获取当前登录用户城市失败:{}", e);
            return "杭州市";
        }
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }
}
